<?php

namespace IDock\Insurance\AMIC\Response;

use IDock\Http\Response;
use IDock\Printer\EPolicyDownloadPrinter;

class EPolicyDownloadResponse extends AllAMICResponse
{
    /**
     * @var EPolicyDownloadPrinter $printer
     */
    public $printer = EPolicyDownloadPrinter::class;

    public $nonCarUrl = [];

    public function resolve(): Response
    {
        $body = $this->getBody();

        if (is_string($this->printer)) {
            $this->printer = new $this->printer;
        }
        if ($body) {
            $body = json_decode($body, true);
            $returnCode = $body['head']['returnCode'] ?? '';
            $message = $body['head']['returnMsg'] ?? '';
            $this->setBody($body);
            if ($returnCode != '0000') {
                $this->setError($message);
                return $this;
            }
        }

        return $this;
    }

    public function printerInit(): Response
    {
        $body = $this->getBody();

        if (is_string($this->printer)) {
            $this->printer = new $this->printer;
        }
        $data = $body['baseInfo'] ?? [];
        $this->printer->finish = true;
        $this->printer->url = $data['url'] ?? '';
        $this->printer->signUrl = $data['JQX_Url'] ?? '';

        foreach ($data['policyUrlList'] ?? '' as $nonCar) {
            $this->nonCarUrl[] = $nonCar['url'] ?? '';
        }

        $this->nonCarUrl = array_filter($this->nonCarUrl);

        if (empty($this->printer->url)) {
            $this->setError('下载电子保单失败');
            $this->printer->doing = true;
            $this->printer->finish = false;
            return $this;
        }
        return $this;
    }
}
